package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyerCarBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyerCarMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyerCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BuyerCarServiceImpl implements IBuyerCarService {
    @Autowired
    private IBuyerCarMapper buyerCarMapper;

    @Autowired
    private IProductMapper productMapper;

    @Override
    public List<BuyerCarBean> findByUserId(Integer userId) {
        return buyerCarMapper.findByUserId(userId);
    }

    @Override
    public void update(Integer buyerCarId, Integer num) {
        BuyerCarBean buyerCar = buyerCarMapper.selectById(buyerCarId);
        buyerCar.setNum(num);
        buyerCarMapper.updateById(buyerCar);


    }

    @Override
    public void del(Integer buyerCarId) {
        buyerCarMapper.deleteById(buyerCarId);
    }

    @Override
    public void add(String option, ProductBean product, Integer unm, Integer userId) {
        //1.判断option 是否为add 如果是 完成库存商品添加
        if (option.equals("add")) {
            product.setNum(0);
            productMapper.insert(product);
        }
        //2.判断是否存在商品 如果不存在 则添加采购车记录
        QueryWrapper<BuyerCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId", product.getId());
        qw.eq("fk_userId", userId);
        BuyerCarBean buyerCar = buyerCarMapper.selectOne(qw);
        if (buyerCar == null) {
            buyerCar = new BuyerCarBean();
            buyerCar.setProductId(product.getId());
            buyerCar.setUserId(userId);
            buyerCar.setNum(unm);
            buyerCar.setMoney(product.getBuyPrice());
            buyerCarMapper.insert(buyerCar);
        } else {//如果购物车中存在该商品则修改采购数量，
            buyerCar.setNum(buyerCar.getNum() + unm);
            buyerCarMapper.updateById(buyerCar);

        }

    }
}

